import { HeadersType, Methods, Options, Params } from "./types";

import { BaseHttp, RequestError } from "./base-http";
import { showLoading, hideLoading } from "./loading";
console.log(import.meta.env.VITE_BASE_URL, "base-utl  *** plugin");

class HttpRequest<T = any> {
	private baseUrl = import.meta.env.VITE_BASE_URL + "/api";

	constructor(private url: string, private options?: Options, private isLoad: boolean = true) {
		this.options = options;
		this.isLoad = isLoad;
	}
	public async get(params?: Params) {
		return await this.send("GET", params);
	}
	public async post(params?: Params, before?: Function) {
		before && before();
		return await this.send("POST", params);
	}
	public async put(params?: Params) {
		return await this.send("PUT", params);
	}
	public async delete(params?: Params) {
		return await this.send("DELETE", params);
	}
	public setBaseUrl(baseUrl: string) {
		this.baseUrl = baseUrl;
		return this;
	}
	private async send(
		method: Methods,
		params?: Params,
		conf?: { isLoading: boolean }
	): Promise<T> {
		const instance = BaseHttp.getInstance();
		if (!conf || conf?.isLoading == undefined) {
			conf = {
				isLoading: true,
			};
		}
		let res!: any;

		showLoading();

		try {
			if (method === "GET") {
				res = await instance({
					// baseURL: this.baseUrl,
					// url: this.url,
					url: this.baseUrl + this.url,
					method,
					params: params || "",
					headers: this.defaultHeader(this.options?.header || HeadersType.Json),
				});
			} else {
				res = instance({
					url: this.baseUrl + this.url,
					method,
					data: params || {},
					headers: this.defaultHeader(this.options?.header || HeadersType.Json),
				});
			}
		} catch (error) {
			console.log(error);
			setTimeout(function () {
				hideLoading();
			}, 200);
		}
		setTimeout(function () {
			hideLoading();
		}, 200);
		return res as Promise<T>;
	}

	private defaultHeader(header: HeadersType) {
		const accessToken = JSON.parse(window.localStorage.getItem("ACCESS_TOKEN") as string);
		return {
			"Content-Type": header,
			// Authorization: accessToken ? `Bearer ${accessToken}` : "",
			Authorization: `Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VySWQiOjEzMDAwMDAwMDAxMDEsIlRlbmFudElkIjoxMzAwMDAwMDAwMDAxLCJBY2NvdW50Ijoic3VwZXJhZG1pbiIsIlJlYWxOYW1lIjoi6LaF57qn566h55CG5ZGYIiwiQWNjb3VudFR5cGUiOjk5OSwiT3JnSWQiOjAsIk9yZ05hbWUiOm51bGwsIk9yZ1R5cGUiOm51bGwsImlhdCI6MTcwNDc2NzI4MiwibmJmIjoxNzA0NzY3MjgyLCJleHAiOjE3MDUzNzIwODIsImlzcyI6IkFkbWluLk5FVCIsImF1ZCI6IkFkbWluLk5FVCJ9.RdavdPIxkPToa8eIoSbTnXvPmnZ6NjC_cCHvi3U_x4E`,
		};
	}
}

export { HttpRequest, BaseHttp, RequestError };
